<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import pinia from '/@/stores';
import api from '/@/api/email/index';
import { useEmail } from '/@/stores/email';
import commonApi from '/@/api/common/index';
import OneUpload from '/@/components/Common/OneUpload.vue'
import { type FormInstance, type FormRules } from 'element-plus'

defineProps({
    modelValue: {
        type: Boolean,
        default: false
    },
})
const emit = defineEmits(['update:modelValue', 'refresh'])
const ruleFormRef = ref<FormInstance[]>()
const stores = useEmail(pinia);
const twoDialogRef = ref()

// 工厂列表
const factoryOptions = ref<{
    id: number
    name: string
}[]>([])
// 付款方式
interface DictType {
    dictLabel: string
    dictValue: string
}
const payTypeData = ref<DictType[]>([])
const payMentTypeData = ref<DictType[]>([])
interface RuleForm {
    id: number | undefined
    factoryInfo: { name: string }
    billAmount: number | undefined
    orderFactoryBillList: any[]
    orderId: number | undefined
    factoryId: number | undefined
    goodsAmount: number | undefined
    payType: number | undefined
    payCertificate: string | any[]
    paymentType: number | undefined
    accountName: string
    accountCode: string
}
const ruleForm = reactive({
    orderId: undefined,
    orderFactoryList: [
        // {
        //     orderFactoryId: undefined,
        //     goodsAmount: undefined,
        //     payType: undefined,
        //     payCertificate: [],
        //     paymentType: undefined,
        //     accountName: '',
        //     accountCode: '',
        // }
    ] as RuleForm[],
})
const rules = reactive<FormRules<RuleForm>>({
    factoryId: [{ required: true, message: '请选择工厂供应商', trigger: 'change' }],
    goodsAmount: [{ required: true, message: '请填写付款金额', trigger: 'change' }],
    payType: [{ required: true, message: '请选择付款方式', trigger: 'change' }],
    payCertificate: [{ required: true, message: '请上传付款凭证', trigger: 'change' }],
    paymentType: [{ required: true, message: '请选择付款类型', trigger: 'change' }],
    accountName: [{ required: true, message: '请填写账户名称', trigger: 'change' }],
    accountCode: [{ required: true, message: '请填写账户号码', trigger: 'change' }],
})
// 查询工厂数据
const getFactoryList = async () => {
    const account = stores.curAccount;
    try {
        const { data } = await api.factory.getList({
            emailAccount: account,
            pageNum: 1,
            pageSize: 999,
        });
        factoryOptions.value = data;
    } catch (error) {
        console.log(error)
    }
};
const getPayTypeData = async () => {
  const { code, data } = await commonApi.getDictData('pay_type');
  if (code === 200) {
    payTypeData.value = data;
  }
};
const getPayMentTypeData = async () => {
  const { code, data } = await commonApi.getDictData('payment_type');
  if (code === 200) {
    payMentTypeData.value = data;
  }
};
const submit = async () => {
    if (ruleFormRef.value?.length) {
        let isValid = true
        for (let k = 0; k < ruleFormRef.value.length; k++) {
            const el = ruleFormRef.value[k]
            await el.validate((valid) => {
                if (isValid && !valid) {
                    isValid = valid
                }
            })
        }
        if (!isValid) {
            return
        }
        const paymentItems = ruleForm.orderFactoryList.map((o) => {
            const { id, goodsAmount, payType, payCertificate, paymentType, accountName, accountCode } = o
            return {
                orderFactoryId: id,
                goodsAmount,
                payType,
                payCertificate: payCertificate && Array.isArray(payCertificate) ? payCertificate.map(n => n.url).join(',') : '',
                paymentType,
                accountName,
                accountCode,
            }
        })
        const { code } = await api.order.addPayment({
            orderId: ruleForm.orderId,
            paymentItems,
        })
        if (code === 200) {
            ElMessage.success('操作成功')
            emit('refresh')
        }
    }
    twoDialogRef.value?.close()
}
const close = async () => {
    if (ruleFormRef.value?.length) {
        for (let k = 0; k < ruleFormRef.value.length; k++) {
            const el = ruleFormRef.value[k]
            await el.resetFields()
        }
    }
    emit('update:modelValue', false)
}


const getInfo = async () => {
    const { data } = await api.order.info(String(ruleForm.orderId))
    if (data.orderFactoryList?.length) {
        // 过滤出需要付尾款并且是业务员对接的数据
        const arrs = data.orderFactoryList.filter((f: { paymentFlag: number; dataType: number; }) => f.paymentFlag === 1 && f.dataType === 1)
        // const arrs = data.orderFactoryList
        arrs.forEach((e: { factoryInfo: string; payCertificate: never[]; accountName: string; accountCode: string; }) => {
            e.factoryInfo = JSON.parse(e.factoryInfo)
            e.payCertificate = []
            e.accountName = ''
            e.accountCode = ''
        })
        ruleForm.orderFactoryList = arrs
    }
}

function calcPaid(list: any[]) {
  let amount = 0
  list.filter((f: { payStatus: number; }) => f.payStatus === 1).forEach((item: { goodsAmount: any; }) => {
    amount += item.goodsAmount || 0
  })
  return amount.toFixed(3)
}

defineExpose({
    ruleForm,
    getInfo
})

onMounted(() => {
    getFactoryList()
    getPayTypeData()
    getPayMentTypeData()
})
</script>
<template>
    <TwoDialog ref="twoDialogRef" id="addFinalPayMent" :modelValue="modelValue" title="添加尾款" width="520px" @submit="submit" @close="close" @minimize="emit('update:modelValue', false)">
        <el-space direction="vertical">
            <el-form v-for="form in ruleForm.orderFactoryList" :key="form.id" ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="auto">
                <el-row :gutter="16">
                    <el-col :span="24">
                        <el-form-item label="工厂供应商" prop="factoryInfo">
                            {{ form.factoryInfo?.name }}
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="订单总金额(RMB)" prop="billAmount">
                            {{ form.billAmount?.toFixed(3) }}
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="已支付金额(RMB)" prop="orderFactoryBillList">
                            {{ calcPaid(form.orderFactoryBillList) }}
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="本次付款金额" prop="goodsAmount">
                            <el-input-number v-model="form.goodsAmount" :min="0" :step="0.001" :precision="3" :controls="false" style="width: 100%;" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="付款方式" prop="payType">
                            <el-radio-group v-model="form.payType">
                                <el-radio v-for="item in payTypeData" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue" />
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="付款凭证" prop="payCertificate">
                            <OneUpload v-model="form.payCertificate" accept="" :limit="15" :maxSize="10"
                                :fileType="[]" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="收款账号类型" prop="paymentType">
                            <el-radio-group v-model="form.paymentType">
                                <el-radio v-for="item in payMentTypeData" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue" />
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="户名" prop="accountName">
                            <el-input v-model="form.accountName" placeholder="请填写账号户名"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="账号" prop="accountCode">
                            <el-input v-model="form.accountCode" placeholder="请填写账号"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </el-space>
        <div v-if="ruleForm.orderFactoryList.length === 0" class="empty">
            暂无需要支付的尾款订单
        </div>
    </TwoDialog>
</template>
<style lang="scss" scoped>
.cascader-panel {
    width: fit-content;
}
.empty {
    padding: 16px;
    text-align: center;
    color: #9ca3af;
}
</style>